#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<dirent.h>
#define ll long long
#ifdef BUFSIZ

#undef BUFSIZ

#define BUFSIZ 4096

#endif

char *getFilename(char *path){
    char filename[1024];
    char *p =path;
    while(*p!='\0') p++;
    while(*p!='/') p--;
    int i = 0;
    while(*p!='\0'){
        filename[i++]=*p;
        p++;
    }
    return filename;
}
int is_dir(char *path){
    struct stat st;
    stat(path, &st);
    if(S_ISDIR(st.st_mode)) return 1;
    else return 0;
}
int copy_file(char *srcPath,char *desPath){
    char buf[BUFSIZ];
    FILE *fp_src,*fp_des;
    if((fp_src=fopen(srcPath,"r"))==NULL){
        fprintf(stderr,"open%s failed!\n",srcPath);
        return -1;
    }
    if((fp_des=fopen(desPath,"w"))==NULL){
        fprintf(stderr,"open/create %s failed!\n",desPath);
        return -1;
        
    }
    while(fgets(buf,BUFSIZ,fp_src)!=NULL){
        if(fputs(buf,fp_des)==EOF){
            fprintf(stderr, "copy %s to %s failed!\n", srcPath, desPath);
			return -1;
        }
    }
    printf("copy %s to %s successful!\n", srcPath, desPath);
    fclose(fp_src);
    fclose(fp_des);
	return 0;
}
int end_with(char *s,char c){
    if(s[strlen(s)-1]==c){
        return 1;
    }else{
        return 0;
    }

}
int copy_fold(char*srcPath,char*desPath){
    char newSrcPath[1024];
    char newDesPath[1024];
    if(mkdir(desPath,0777)){
        printf("目录已存在！\n");
        return -1;
    }
    DIR *srcDp = opendir(srcPath);
    if(srcDp==NULL){
        printf("文件%s打开失败！\n",srcPath);
        return -1;
    }
    struct dirent *srcDirent =NULL;
    while(srcDirent ==readdir(srcDp)){
        bzero(newSrcPath,sizeof(newSrcPath));
        bzero(newDesPath,sizeof(newSrcPath));
        sprintf(newSrcPath,"%s%s",srcPath,srcDirent->d_name);
        sprintf(newDesPath,"%s%s",desPath,srcDirent->d_name);
        if(srcDirent->d_type ==DT_DIR){
            if(!end_with(newDesPath,'.')){
                copy_fold(newSrcPath,newDesPath);
            }else{
                copy_file(newSrcPath,newDesPath);
            }
        }
        return 0;
        
    }
}
int main(int argc,char** argv){
   
    // int msglen;
    if(argc !=3 ||strcmp(argv[1],argv[2])==0){
        fprintf(stderr, "********************************\n\n");

		fprintf(stderr, "Please usage:%s source_file destination_file\nAnd source_file is different from destination_file\n\n", argv[0]);

		fprintf(stderr, "********************************\n");

		exit(0);

    }
    char *srcPath = argv[1];
    char *desPath = argv[2];
    if(is_dir(srcPath)){
        copy_fold(srcPath,desPath);
    }else{
        if(access(desPath,F_OK)==0){
            sprintf(desPath,"%s%s",desPath,getFilename(srcPath));
        }
        copy_file(srcPath,desPath);
    }
    return 0;
    
}